package com.ruoyi.payOrder.order.listener;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.rabbitmq.client.Channel;
import com.ruoyi.common.core.constant.OrderStatusConstants;
import com.ruoyi.payOrder.order.domain.Order;
import com.ruoyi.payOrder.order.mapper.OrderMapper;
import com.ruoyi.payOrder.order.service.IOrderService;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.context.annotation.Configuration;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.io.IOException;

@Component
public class OrderStatusModifyListener {


    @Resource
    private RabbitTemplate rabbitTemplate;

    @Resource
    private OrderMapper orderMapper;

    @Resource
    private ObjectMapper objectMapper;


    private Integer retryCount=0;
    private final Integer MAX_RETRY_COUNT=3;

    /**
     * 监听死信队列，负责修改订单的状态
     * @param message
     * @param channel
     * @throws IOException
     */
    @RabbitListener(queues = "order_status_queue")
    public void orderStatusModify(Message message, Channel channel) throws IOException {



        //获取到MQ中的信息
        Long orderId = (Long) rabbitTemplate.getMessageConverter().fromMessage(message);

        System.out.println("此时订单的状态"+orderId);

        //查询数据库，获取到订单信息
        Order order = orderMapper.selectOrderById(orderId);

        //如果订单状态为待支付，那么就修改订单状态为已取消

        if (OrderStatusConstants.PENDING_PAYMENT== order.getStatus()){
            //修改订单的状态
            order.setStatus(OrderStatusConstants.CANCELLED);
            System.out.println(order);
            //存入数据库
            int rows = orderMapper.updateOrder(order);

            System.out.println(rows);

            if (rows > 0){
                channel.basicAck(message.getMessageProperties().getDeliveryTag(),true);
            }else if (retryCount<MAX_RETRY_COUNT){
                retryCount++;
                channel.basicNack(message.getMessageProperties().getDeliveryTag(),true,true);
            }else {
                channel.basicNack(message.getMessageProperties().getDeliveryTag(),true,false);
            }
        }else {
            System.out.println("订单已支付，不需要额外操作");
        }

    }
}
